const chokidar = require('chokidar')
const fs = require('fs');
let path = require("path");
function setSubPages() {
let pagesJson = {
	"pages":[
		{
			"path": "pages/my/userSetting/index",
			"style": {
				"navigationBarTitleText": "账号设置"
			}
		}

	] ,
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "uni-app",
		"navigationBarBackgroundColor": "#F8F8F8",
		"backgroundColor": "#F8F8F8"
	},
	"tabBar": {
		"color": "#7A7E83",
		"selectedColor": "#007AFF",
		"borderStyle": "black",
		"backgroundColor": "#F8F8F8",
		"list": [
			{
				"pagePath": "pages/index/index",
				"iconPath": "./static/nav-logo/index.png",
				"selectedIconPath": "./static/nav-logo/index-active.png",
				"text": "选品库"
			},
			{
				"pagePath": "pages/seo/index",
				"iconPath": "./static/nav-logo/seo.png",
				"selectedIconPath": "./static/nav-logo/seo-active.png",
				"text": "搜索"
			}, 
			{
				"pagePath": "pages/recommend/index",
				"iconPath": "./static/nav-logo/recommend.png",
				"selectedIconPath": "./static/nav-logo/recommend-active.png",
				"text": "推荐专题"
			},			
			{
				"pagePath": "pages/my/index",
				"iconPath": "./static/nav-logo/mine.png",
				"selectedIconPath": "./static/nav-logo/mine-active.png",
				"text": "我的66"
			}
		]
	}
}


	let routers = JSON.parse(JSON.stringify(pagesJson.pages))
	let pathList = []
	for (let item of routers) {
		pathList.push(item.path)
	}
	// 初始化router
	let myurl = "./pages"

	return new Promise((reject, resove) => {
		function myReadfile(MyUrl, callback) {
			fs.readdir(MyUrl, (err, files) => {
				let count = 0
				let checkEnd = function() {
					if (++count == files.length) {
						callback()
					}
				}
				if (err) throw err
				files.forEach(file => {
					//拼接获取绝对路径，fs.stat(绝对路径,回调函数)
					let fPath = path.join(MyUrl, file);
					fs.stat(fPath, (err, stat) => {
						//stat 状态中有两个函数一个是stat中有isFile ,isisDirectory等函数进行判断是文件还是文件夹
						if (stat.isFile()) {
							let path = fPath.replace('.vue', '').replace(/\\/g, '/')
							// console.log(path,file)
							// 判断是否已经存在写死的路由
							if (!pathList.includes(path)) {
								// 获取页面的navigationBarTitleText
								let vue_res = fs.readFileSync(fPath, "utf8")
								let text = vue_res.match(/nbtitle:(\S*);/)
								if(text){
									text = text[1]
								}
								routers.push({
									"path": path,
									"style": {
										"navigationBarTitleText": text||path
									}
								})
							}
							checkEnd()
						} else {
							myReadfile(fPath, checkEnd)
						}
					})
				})
			})
		}
		let timeStart = new Date()
		myReadfile(myurl, function(filePath) {
			console.log('done', new Date() - timeStart);
			pagesJson.pages = JSON.parse(JSON.stringify(routers))
			writePagesJson(pagesJson)
			reject(routers)
		})
	})
}


function writePagesJson(pagesJson){
	fs.writeFileSync("./pages.json", JSON.stringify(pagesJson) );
	console.log('更新pages.json成功')
}


function watchPages() {

	let watcher = null
	let ready = false
	// 文件新增时
	function addFileListener(path_) {
		if (ready) {
			console.log('文件', path_, '被添加了')
			needUpdateLib(path_, 'update')
		}
	}

	function addDirecotryListener(path_) {
		if (ready) {
			console.log('目录', path_, '被添加了')
			needUpdateLib(path_, 'update')
		}
	}

	// 文件内容改变时
	function fileChangeListener(path_) {
		console.log('文件', path_, '已经修改')
		needUpdateLib(path_, 'update')
	}

	// 删除文件
	function fileRemovedListener(path_) {
		console.log('文件', path_, '被删除了')
		needUpdateLib(path_, 'remove')
	}

	// 删除目录时
	function directoryRemovedListener(path_) {
		// ./lib_mb/build/pcom
		// E:\work\codewarehouse\vue-lib-factory\lib_mb\dev\pcom
		if (path_.indexOf('vue-lib-factory') == -1) {
			path_ = path_.replace('./', '')
			path_ = path_.replace('/', '\\')
		} else {
			console.log('lsjdlaj', path_.split('vue-lib-factory\\')[1])
			path_ = path_.split('vue-lib-factory\\')[1]
		}
		console.info('目录', path_, '被删除了')
		needUpdateLib(path_, 'remove')

	}

	function needUpdateLib(path) {
		setSubPages()
	}

	if (!watcher) {
		watcher = chokidar.watch('./pages')
	}
	watcher
		.on('add', addFileListener)
		.on('addDir', addDirecotryListener)
		// .on('change', fileChangeListener)
		.on('unlink', fileRemovedListener)
		.on('unlinkDir', directoryRemovedListener)
		.on('error', function(error) {
			console.info('发生了错误：', error);
		})
		.on('ready', function() {
			console.info('正在监听');
			ready = true
		})
}

setSubPages()
watchPages()
module.exports = {
	setSubPages,
	watchPages
}
